/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * telaSaida.java
 *
 * Created on 08/12/2012, 19:47:44
 */
package gui;

import Fachada.Fachada;
import classes.ItensProduto;
import classes.Produto;
import classes.Saida;
import classes.teclasPermitidas;
import erro.ConexaoException;
import erro.ConsultaException;
import erro.DaoException;
import erro.GeralException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Random;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;

/**
 *
 * @author George
 */
public class telaSaida extends javax.swing.JFrame {

    private static Fachada f;

    /** Creates new form telaSaida */
    public telaSaida() {
        initComponents();
        this.setLocationRelativeTo(null);
        LabelDataSaida.setText(getDateTime());
        txtBoxQuantItens.setDocument(new teclasPermitidas());
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jLabel1 = new javax.swing.JLabel();
        txtBoxPesqProd = new javax.swing.JTextField();
        jButtonPesqProd = new javax.swing.JButton();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();
        jButtonSalvarSaida = new javax.swing.JButton();
        jButtonCancelarSaida = new javax.swing.JButton();
        jLabelLote = new javax.swing.JLabel();
        jButtonPesqLote = new javax.swing.JButton();
        jScrollPane1 = new javax.swing.JScrollPane();
        TableLotesProd = new javax.swing.JTable();
        LabelDataSaida = new javax.swing.JLabel();
        jLabel5 = new javax.swing.JLabel();
        jSeparator1 = new javax.swing.JSeparator();
        txtBoxQuantItens = new javax.swing.JTextField();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jLabel1.setText("Produto:");

        jButtonPesqProd.setText("Pesquisar");
        jButtonPesqProd.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonPesqProdActionPerformed(evt);
            }
        });

        jLabel2.setText("Num. Lote:");

        jLabel3.setText("Quant. Itens:");

        jLabel4.setText("Data Saida:");

        jButtonSalvarSaida.setText("SALVAR");
        jButtonSalvarSaida.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonSalvarSaidaActionPerformed(evt);
            }
        });

        jButtonCancelarSaida.setText("CANCELAR");
        jButtonCancelarSaida.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonCancelarSaidaActionPerformed(evt);
            }
        });

        jButtonPesqLote.setText("Pesquisar Lote");
        jButtonPesqLote.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonPesqLoteActionPerformed(evt);
            }
        });

        TableLotesProd.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null},
                {null, null, null},
                {null, null, null},
                {null, null, null}
            },
            new String [] {
                "Num. Lote", "Quant. Itens Disponíveis", "Data Validade"
            }
        ));
        TableLotesProd.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                TableLotesProdMouseClicked(evt);
            }
        });
        jScrollPane1.setViewportView(TableLotesProd);

        LabelDataSaida.setFont(new java.awt.Font("Tahoma", 0, 12));

        jLabel5.setFont(new java.awt.Font("Tahoma", 0, 36));
        jLabel5.setText("Saida de Produto");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap(43, Short.MAX_VALUE)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(11, 11, 11)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createSequentialGroup()
                                .addGap(10, 10, 10)
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addGroup(layout.createSequentialGroup()
                                        .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                                        .addGap(18, 18, 18)
                                        .addComponent(jButtonPesqLote))
                                    .addGroup(layout.createSequentialGroup()
                                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                                            .addComponent(jLabel1)
                                            .addComponent(jLabel4))
                                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                            .addComponent(LabelDataSaida, javax.swing.GroupLayout.PREFERRED_SIZE, 111, javax.swing.GroupLayout.PREFERRED_SIZE)
                                            .addGroup(layout.createSequentialGroup()
                                                .addComponent(txtBoxPesqProd, javax.swing.GroupLayout.PREFERRED_SIZE, 282, javax.swing.GroupLayout.PREFERRED_SIZE)
                                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                                .addComponent(jButtonPesqProd, javax.swing.GroupLayout.PREFERRED_SIZE, 109, javax.swing.GroupLayout.PREFERRED_SIZE))))))
                            .addGroup(layout.createSequentialGroup()
                                .addGap(191, 191, 191)
                                .addComponent(jButtonSalvarSaida, javax.swing.GroupLayout.PREFERRED_SIZE, 89, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addGap(18, 18, 18)
                                .addComponent(jButtonCancelarSaida, javax.swing.GroupLayout.PREFERRED_SIZE, 99, javax.swing.GroupLayout.PREFERRED_SIZE))
                            .addGroup(layout.createSequentialGroup()
                                .addGap(13, 13, 13)
                                .addComponent(jLabel2)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                .addComponent(jLabelLote, javax.swing.GroupLayout.PREFERRED_SIZE, 145, javax.swing.GroupLayout.PREFERRED_SIZE))
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(jLabel3)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(txtBoxQuantItens, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE))))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(115, 115, 115)
                        .addComponent(jSeparator1, javax.swing.GroupLayout.PREFERRED_SIZE, 326, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addGap(42, 42, 42))
            .addGroup(layout.createSequentialGroup()
                .addGap(201, 201, 201)
                .addComponent(jLabel5)
                .addContainerGap(206, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(jLabel5)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jSeparator1, javax.swing.GroupLayout.PREFERRED_SIZE, 10, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(18, 18, 18)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jLabel4)
                            .addComponent(LabelDataSaida, javax.swing.GroupLayout.PREFERRED_SIZE, 14, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addGap(18, 18, 18)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jLabel1)
                            .addComponent(jButtonPesqProd)
                            .addComponent(txtBoxPesqProd, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addGap(21, 21, 21)
                        .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 133, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(18, 18, 18)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel2)
                            .addComponent(jLabelLote, javax.swing.GroupLayout.PREFERRED_SIZE, 20, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jLabel3)
                            .addComponent(txtBoxQuantItens, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addGap(31, 31, 31)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jButtonSalvarSaida, javax.swing.GroupLayout.PREFERRED_SIZE, 38, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jButtonCancelarSaida, javax.swing.GroupLayout.DEFAULT_SIZE, 38, Short.MAX_VALUE)))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(184, 184, 184)
                        .addComponent(jButtonPesqLote, javax.swing.GroupLayout.PREFERRED_SIZE, 45, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void jButtonPesqProdActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonPesqProdActionPerformed
        Produto prod = new Produto();
        f = Fachada.getInstancia();
        prod.setDescProduto(txtBoxPesqProd.getText());
        if (prod.getDescProduto() != null) {
            telaPesquisarProduto tlpesqprod = new telaPesquisarProduto();
            tlpesqprod.setVisible(true);
        } else {
            try {
                f.pesquisarProd(prod);

            } catch (DaoException e) {
                JOptionPane.showMessageDialog(null, e.getMessage());
            } catch (GeralException ex) {
                JOptionPane.showMessageDialog(null, ex.getMessage());
            }
        }
    }//GEN-LAST:event_jButtonPesqProdActionPerformed

    private void jButtonSalvarSaidaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonSalvarSaidaActionPerformed
        f = Fachada.getInstancia();
        Produto prod = new Produto();
        prod.setDescProduto(txtBoxPesqProd.getText());
        try {
            f.pesquisarProd(prod);
        } catch (DaoException e) {
            JOptionPane.showMessageDialog(null, e.getMessage());
        } catch (GeralException ex) {
            JOptionPane.showMessageDialog(null, ex.getMessage());
        }

        Saida saida = new Saida();
        ItensProduto itensprod = new ItensProduto();

        // *********************Gerar um codigo*******************
        try {
            String str = "1234567890ABCDEFGHIJKLMNOPQRSTUVWXYZ";
            StringBuffer sb = new StringBuffer();
            Random random = new Random();
            String codigo = new String();
            for (int i = 0; i < 36; ++i) {
                sb.append(str.charAt(random.nextInt(36)));
            }
            for (int j = 0; j < 6; j++) {
                codigo = codigo + String.valueOf(sb.charAt(j));
            }
            //setando o codidentsaida
            saida.setCodidentsaida(codigo.toString());
        } catch (Exception e) {
            // JOptionPane.showMessageDialog(null, "Erro ao tentar gerar o Codigo!");
        }
        // *****************************************************
        saida.setDataSaida(LabelDataSaida.getText());
        saida.setCodProduto(prod);
        saida.setNumLote(jLabelLote.getText());
        saida.setQtdSaidaItens(Integer.parseInt(txtBoxQuantItens.getText()));
        itensprod.setNumLote(jLabelLote.getText());

        prod.setCodProduto(prod.getCodProduto());
        try {
            f.inserirSaida(saida, itensprod, prod);
            limpar();
        } catch (DaoException e) {
            JOptionPane.showMessageDialog(null, e.getMessage());
        } catch (ConsultaException ex) {
            JOptionPane.showMessageDialog(null, ex.getMessage());
        } catch (ConexaoException ex) {
            JOptionPane.showMessageDialog(null, ex.getMessage());
        } catch (GeralException e) {
            JOptionPane.showMessageDialog(null, e.getMessage());
        }
    }//GEN-LAST:event_jButtonSalvarSaidaActionPerformed

    private void jButtonPesqLoteActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonPesqLoteActionPerformed
        TableLotesProd.getColumnModel().getColumn(0).setPreferredWidth(200);
        TableLotesProd.getColumnModel().getColumn(1).setPreferredWidth(200);
        TableLotesProd.getColumnModel().getColumn(2).setPreferredWidth(200);
        DefaultTableModel modelo = (DefaultTableModel) TableLotesProd.getModel();
        modelo.setNumRows(0);
        f = Fachada.getInstancia();
        Produto prod = new Produto();
        prod.setDescProduto(txtBoxPesqProd.getText());
        try {
            f.pesquisarProd(prod);
        } catch (DaoException e) {
            JOptionPane.showMessageDialog(null, e.getMessage());
        } catch (GeralException ex) {
            JOptionPane.showMessageDialog(null, ex.getMessage());
        }
        ItensProduto ip = new ItensProduto();
        ArrayList<ItensProduto> lista = new ArrayList<ItensProduto>();

        try {
            ip.setCodProduto(prod);
            lista = (ArrayList<ItensProduto>) f.listar(ip);

        } catch (ConexaoException ex) {
            JOptionPane.showMessageDialog(null, ex.getMessage());
        } catch (ConsultaException ex) {
            JOptionPane.showMessageDialog(null, ex.getMessage());
        }
        for (int i = 0; i < lista.size(); i++) {
            if (lista.get(i).getQuantItens() == 0) {
                //
            } else {
                modelo.addRow(new Object[]{lista.get(i).getNumLote(), lista.get(i).getQuantItens(), lista.get(i).getDataValidade()});
            }
        }
        TableLotesProd.setModel(modelo);
    }//GEN-LAST:event_jButtonPesqLoteActionPerformed

    private void TableLotesProdMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_TableLotesProdMouseClicked
        int x = TableLotesProd.getSelectedRow();
        int y = TableLotesProd.getSelectedColumn();

        //Se o clique for unico
        if (evt.getClickCount() == 1) {
            if (evt.getButton() == evt.BUTTON1) {//E o botão for o esquerdo

                jLabelLote.setText((String) TableLotesProd.getValueAt(x, 0));
            }
        }
    }//GEN-LAST:event_TableLotesProdMouseClicked

    private void jButtonCancelarSaidaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonCancelarSaidaActionPerformed
        telaSaida tlsaida = new telaSaida();
        int i = JOptionPane.showConfirmDialog(null, "Deseja realmente Cancelar?", "Cancelar", JOptionPane.YES_NO_OPTION);
        if (i == JOptionPane.YES_OPTION) {
            telaSaida.this.setVisible(false);
            tlsaida.dispose();
        } else {
            repaint();
        }
    }//GEN-LAST:event_jButtonCancelarSaidaActionPerformed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(telaSaida.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(telaSaida.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(telaSaida.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(telaSaida.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                new telaSaida().setVisible(true);

            }
        });
    }

    public void limpar() {
        txtBoxPesqProd.setText("");
        DefaultTableModel tableModel = (DefaultTableModel) TableLotesProd.getModel();
        tableModel.setNumRows(0);
        txtBoxQuantItens.setText("");

    }

    private String getDateTime() {
        DateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");
        Date date = new Date();
        return dateFormat.format(date);
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JLabel LabelDataSaida;
    private javax.swing.JTable TableLotesProd;
    private javax.swing.JButton jButtonCancelarSaida;
    private javax.swing.JButton jButtonPesqLote;
    private javax.swing.JButton jButtonPesqProd;
    private javax.swing.JButton jButtonSalvarSaida;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    public javax.swing.JLabel jLabelLote;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JSeparator jSeparator1;
    public javax.swing.JTextField txtBoxPesqProd;
    private javax.swing.JTextField txtBoxQuantItens;
    // End of variables declaration//GEN-END:variables
}
